'use strict';

const Controller = require('egg').Controller;
const UAParser = require('ua-parser-js');

class MonitorController extends Controller {
  async index() {
    const { ctx , service} = this;
    ctx.body = await service.monitor.index();
  }
  /**
   * 日志上报接口
   */
  async report(){
    const { ctx , service, request} = this;
    // 数据预处理
		// 获取基础信息
		let {list,type} = ctx.request.body;
    // 获取错误上报信息
    if(typeof list == 'string') list = JSON.parse(list);
    if(!list || !list.length) return ctx.success([])
    // -------判断是否有device上传----------
    const deviceInfo = list.findIndex(item => item.report_type == 'device')
    if(deviceInfo>=0){
        this.device(list[deviceInfo])
        list.splice(deviceInfo,1)
    }
    // 数据保存到数据库
    const result = await service.wx.monitor.saveToRedis(list);
    console.log("【report】:",result)
    ctx.success(result)
  }
  /**
   * 设备信息上报
   */
  async device(deviceInfo){
    const { ctx , service, request} = this;
    const ip = ctx.get('X-Real-IP') || ctx.get('X-Forwarded-For') || ctx.ip // 先判断真是ip，在判断代理ip，ctx.ip
    const user_agent = ctx.headers['user-agent'];
		const {mark_user} = deviceInfo;

    // 客户端信息
    const parser = new UAParser();
    parser.setUA(user_agent);
    const userAgent = parser.getResult();
    const device = {mark_user,ip}
    device.browser = userAgent.browser.name || '';
    device.borwser_version = userAgent.browser.version || '';
    device.system = userAgent.os.name || '';
    device.system_version = userAgent.os.version || '';
    // 开始保存
    const result = await this.app.model.Device.create(device) ;

    ctx.success(result)
  }
}

module.exports = MonitorController;
